//
//  PersonalEditController.m
//  renmingongshe
//
//  Created by Mao on 2017/11/8.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "PersonalEditController.h"
#import "THWAlertControler.h"
#import "SelectOnePicture.h"

@interface PersonalEditController ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    NSArray *_sexArr;
    NSString *_photo;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *botton;

@property (strong, nonatomic) SelectOnePicture *OnePicture;
@property (strong, nonatomic)UIView* BtnbackView;
@property (strong, nonatomic)UIPickerView* pickerView;

@property (weak, nonatomic) IBOutlet UILabel *processLb;
@property (weak, nonatomic) IBOutlet UIImageView *imaview;
@property (weak, nonatomic) IBOutlet UIView *processView;
@property (weak, nonatomic) IBOutlet UIButton *commitBtn;
@property (weak, nonatomic) IBOutlet UITextField *UserNameTF;
@property (weak, nonatomic) IBOutlet UIButton *SexBtn;
@property (weak, nonatomic) IBOutlet UITextField *AgeTF;
@property (weak, nonatomic) IBOutlet UITextField *PhoneTF;
@property (weak, nonatomic) IBOutlet UITextField *WeixinTF;
@property (weak, nonatomic) IBOutlet UITextField *UserIdTF;
@property (weak, nonatomic) IBOutlet UITextField *FavoTF;
@property (weak, nonatomic) IBOutlet UITextField *MarryTF;
@property (weak, nonatomic) IBOutlet UITextField *BirthTF;
@property (weak, nonatomic) IBOutlet UITextField *EduTF;
@property (weak, nonatomic) IBOutlet UITextField *JobTF;
@property (weak, nonatomic) IBOutlet UITextField *FatherTF;
@property (weak, nonatomic) IBOutlet UITextField *MontherTF;
@property (weak, nonatomic) IBOutlet UITextField *FarJobTF;
@property (weak, nonatomic) IBOutlet UITextField *MonJobTF;
@property (weak, nonatomic) IBOutlet UITextField *FarBirthTF;
@property (weak, nonatomic) IBOutlet UITextField *MonBirthTF;
@end

@implementation PersonalEditController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"个人资料";
    self.view.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    _commitBtn.layer.cornerRadius = 5;
    _commitBtn.layer.borderWidth= 1;
    _commitBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    
    _sexArr = @[@"男",@"女"];
    [self initView];
}
- (void)initView
{
    NSDictionary *dic = _data;
    _AgeTF.text = [NSString stringWithFormat:@"%@",dic[@"userAge"]];
    _UserNameTF.text = [NSString stringWithFormat:@"%@",dic[@"userName"]];
    _PhoneTF.text = [NSString stringWithFormat:@"%@",dic[@"userPhone"]];
    _WeixinTF.text = [NSString stringWithFormat:@"%@",dic[@"userWei"]];
    [_SexBtn setTitle:[dic[@"userSex"]integerValue]?@"男":@"女" forState:UIControlStateNormal];
    [_imaview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@",dic[@"userPhoto"]]] placeholderImage:[UIImage imageNamed:@"morentouxiang"]];
    _photo = dic[@"userPhoto"];
    
    NSInteger com = [_data[@"complete"]integerValue];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _processView.width*com/100, _processView.height)];
    [_processView addSubview:line];
    line.backgroundColor = [UIColor greenColor];
    line.layer.cornerRadius = 5;
    
    _processLb.text = [NSString stringWithFormat:@"资料完善度% ld%%（资料完善度增加信用度)",com];
    _BirthTF.text = [NSString stringWithFormat:@"%@",dic[@"brithday"]];
    _EduTF.text = [NSString stringWithFormat:@"%@",dic[@"degree"]];
    _UserIdTF.text = [NSString stringWithFormat:@"%@",dic[@"userCardNo"]];
    _FavoTF.text = [NSString stringWithFormat:@"%@",dic[@"userLove"]];
    _MarryTF.text = [NSString stringWithFormat:@"%@",dic[@"userMarry"]];
    _JobTF.text = [NSString stringWithFormat:@"%@",dic[@"work"]];
    
    _FatherTF.text = [NSString stringWithFormat:@"%@",dic[@"fName"]];
    _FarJobTF.text = [NSString stringWithFormat:@"%@",dic[@"fWork"]];
    _FarBirthTF.text = [NSString stringWithFormat:@"%@",dic[@"fBrithday"]];
    
    _MonJobTF.text = [NSString stringWithFormat:@"%@",dic[@"mName"]];
    _MonJobTF.text = [NSString stringWithFormat:@"%@",dic[@"mWork"]];
    _MonBirthTF.text = [NSString stringWithFormat:@"%@",dic[@"mBrithday"]];
}
- (IBAction)commitClick:(id)sender {
    
    NSInteger sex = [_SexBtn.currentTitle isEqualToString:@"男"]?1:0;
    NSDictionary *para = @{@"mBrithday":_MonBirthTF.text,@"mWork":_MonJobTF.text,@"mName":_MontherTF.text,@"fBrithday":_FarBirthTF.text,@"fWork":_FarJobTF.text,@"fName":_FatherTF.text,@"work":_JobTF.text,@"userMarry":_MarryTF.text,@"userLove":_FavoTF.text,@"userCardNo":_UserIdTF.text,@"degree":_EduTF.text,@"brithday":_BirthTF.text,@"userPhoto":_photo,@"userSex":@(sex),@"userWei":_WeixinTF.text,@"userPhone":_PhoneTF.text,@"userName":_UserNameTF.text,@"userAge":_AgeTF.text,@"userToken":[Utils getUserToken]};
    
    [THWManager PostHttp:API(MineInfoCommit) Parameters:para Success:^(id responseObject) {
        
        [self.view Message:responseObject[@"msg"]];
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        if ([responseObject[@"status"]integerValue]) {
            [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"ChangUI" object:nil]];
            
            NSInteger i = [responseObject[@"data"][@"complete"]integerValue];
            [self changeUI:i];
        }
        
    } andFalse:^(NSError *error) {

    }];
}
- (void)changeUI:(NSInteger)i
{
    [_processView removeAllSubviews];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _processView.width*i/100, _processView.height)];
    [_processView addSubview:line];
    line.backgroundColor = [UIColor greenColor];
    line.layer.cornerRadius = 5;
    
    _processLb.text = [NSString stringWithFormat:@"资料完善度% ld%%（资料完善度增加信用度)",i];
    self.back(i);
}
- (IBAction)changIma:(id)sender {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {  // 没权限，提醒用户开启权限
        THWAlertControler *qq = [[THWAlertControler alloc]init];
        UIAlertController *alert = [qq alertmessage:@"请先允许店猫访问你的相册及相机功能，前往设置？" Title:nil andBlock:^{
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // 调用相册
    if (!_OnePicture) {
        _OnePicture = [[SelectOnePicture alloc]initWithFrame:CGRectZero];
        _OnePicture.ratioOfWidthAndHeight = 200/200;
        _OnePicture.enableCutImg  =YES;
        _OnePicture.superController = self;
    }
    // 点击相册的回调
    [_OnePicture toSelectImage:^(NSData *imageData) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"post_disappear"  object:nil];
        //        NSString *tempstr = API(MineShopIma);
        //        [weakSelf imageUpload:imageData withUrl:tempstr];
        
        [self imageUpload:imageData withUrl:API(MineInfoPhoto)];
    }];
}
- (void)imageUpload:(NSData*)data withUrl:(NSString *)url
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    NSDictionary *dic = @{@"name":@"upload_file",@"type":@"image/png",@"tmp_name":fileName,@"size":@(data.length)};
    NSDictionary *para = @{@"flag":@"3",@"upload_file":@[dic], @"userToken":[Utils getUserToken]};
    [self.view loadingOnAnyView];
    [THWManager PostImageWithData:url imageData:data otherParamters:para success:^(NSURLSessionDataTask *task, id responseObject) {
        [self.view removeAnyView];
        [self.view Message:@"上传成功"];
        
        _photo = responseObject[@"data"][@"msg"];
         [_imaview sd_setImageWithURL:[NSURL URLWithString:[Utils getImaSting:responseObject[@"data"][@"msg"]]] placeholderImage:[UIImage imageNamed:@"morentouxiang"]];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.view removeAnyView];
        [self.view Message:@"请重新上传"];
    }];
}
- (IBAction)chooseSex:(id)sender {
    
    self.BtnbackView.hidden = NO;
}
- (UIView *)BtnbackView
{
    if (!_BtnbackView) {
        _BtnbackView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT-230, WIDTH, 230)];
        _BtnbackView.backgroundColor = [UIColor colorWithHex:0x999999];
        _BtnbackView.hidden = YES;
        [self.view addSubview:_BtnbackView];
        
        [_BtnbackView addSubview:self.pickerView];
    }
    return _BtnbackView;
}
- (UIPickerView *)pickerView
{
    if (!_pickerView) {
        [self createPickerView];
    }
    return _pickerView;
}
- (void)createPickerView
{
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, WIDTH, 200)];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    _pickerView.backgroundColor = [UIColor colorWithHex:0x999999];
    [_pickerView selectRow:0 inComponent:0 animated:YES];
    
    
    UIButton* _canceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _canceBtn.frame = CGRectMake(10, 10, 50, 30);
    [_canceBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_canceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_canceBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [_BtnbackView addSubview:_canceBtn];
    [_BtnbackView addSubview:_pickerView];
}
- (void)btnClick
{
    self.BtnbackView.hidden = YES;
}

#pragma mark - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _sexArr.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *str = _sexArr[row];
    return str;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [_SexBtn setTitle:_sexArr[row] forState:UIControlStateNormal];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self registNotification];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self removeNotification];
}
- (void)removeNotification
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)registNotification
{
    // 监听键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyBoard:) name:UIKeyboardWillShowNotification object:nil];
    
    // 监听键盘收起
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hideKeyBoard:) name:UIKeyboardWillHideNotification object:nil];
}
-(void)showKeyBoard:(NSNotification *)notificaiton
{
    CGRect keyboardFrame = [[notificaiton.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat keyboardHeight = keyboardFrame.size.height;
    
    _botton.constant = keyboardHeight;
}

-(void)hideKeyBoard:(NSNotification *)notificaiton
{
    _botton.constant = 0;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
